package cn.gailvlun.gll.presentation.apartment.room

import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import cn.gailvlun.gll.R
import cn.gailvlun.gll.bean.SelectHolder
import cn.gailvlun.gll.databinding.ItemCreateGroupBinding
import cn.gailvlun.gll.net.HttpMethods
import cn.gailvlun.gll.net.HttpSubscriber
import cn.gailvlun.gll.net.ListRes
import cn.gailvlun.gll.net.QueryParam
import cn.gailvlun.gll.net.base.Profile
import cn.gailvlun.gll.presentation.base.BaseActivity
import cn.gailvlun.gll.presentation.chat.adapter.CreateGroupAdapter
import cn.gailvlun.gll.util.DialogUtil
import cn.gailvlun.gll.util.RxUtil
import cn.gailvlun.gll.util.ToastUtil
import cn.gailvlun.gll.widget.CommonItemDecoration
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener
import io.reactivex.Observable
import kotlinx.android.synthetic.main.activity_add_owner.*
import rx_activity_result2.Result
import rx_activity_result2.RxActivityResult

class AddOwnerActivity: BaseActivity(), OnLoadmoreListener {

    companion object {
        fun openActivity(context: Activity): Observable<Result<Activity>> {
            return RxActivityResult.on(context)
                    .startIntent(Intent(context, AddOwnerActivity::class.java))
        }
    }

    private var mAdapter : CreateGroupAdapter? = null
    private var mLayoutManager: LinearLayoutManager? = null

    private var mQueryParam = QueryParam()

    override fun initComponent() {
        setContentView(R.layout.activity_add_owner)

        mAdapter = CreateGroupAdapter(mContext)
        recycler_view.adapter = mAdapter
        mAdapter?.setDecorator { holder, _, _ ->
            (holder.binding as ItemCreateGroupBinding).apply {
                this.root.setOnClickListener {
                    if (mAdapter?.getHowManySelected()!! > 5) {
                        ToastUtil.showShort("最多添加五名小房主")
                        return@setOnClickListener
                    }
                    item?.selected = !item?.selected!!
                    holder.binding.invalidateAll()

                    invalidateMenu()
                }
            }
        }

        mLayoutManager = LinearLayoutManager(mContext)
        recycler_view.layoutManager = mLayoutManager

        srl.setOnLoadmoreListener(this)
        srl.isEnableRefresh = false

        recycler_view.addItemDecoration(CommonItemDecoration(73, 0, 1, resources.getColor(R.color.line_color), Color.WHITE))

        invalidateMenu()
    }

    private fun invalidateMenu() {
        val selectedCount = mAdapter?.getHowManySelected()
        if (selectedCount!! < 2) {
            nbv.setMenuEnable(false)
            nbv.setMenuText("确认")
        } else {
            nbv.setMenuEnable(true)
            nbv.setMenuText("确认($selectedCount)")
        }
    }

    override fun createHandler() {
        nbv.setOnBackListener {
            onBackPressed()
        }

        nbv.setOnMenuClickListener {
            val userList = mAdapter?.getSelectIdList()
            val intent = Intent()
            intent.putIntegerArrayListExtra("userId", ArrayList(userList))
            setResult(Activity.RESULT_OK, intent)
            finish()
        }
    }

    override fun loadData(savedInstanceState: Bundle?) {
        mQueryParam.resetPage()
        HttpMethods.getFriendService()
                .getFriends(mQueryParam.page)
                .compose(bindToLifecycle())
                .compose(RxUtil.applyScheduler())
                .subscribe(object: HttpSubscriber<ListRes<Profile>>() {
                    override fun onSuccess(response: ListRes<Profile>) {
                        mAdapter?.set(SelectHolder.transform(response.results))
                        srl.isEnableLoadmore = response.isNext
                    }

                    override fun onFailure(errMsg: String?, response: ListRes<Profile>?, code: Int) {
                        DialogUtil.showError(mContext, errMsg)
                    }
                })
    }

    override fun onLoadmore(refreshlayout: RefreshLayout?) {
        mQueryParam.nextPage()
        HttpMethods.getFriendService()
                .getFriends(mQueryParam.page)
                .compose(bindToLifecycle())
                .compose(RxUtil.applyScheduler())
                .subscribe(object: HttpSubscriber<ListRes<Profile>>() {
                    override fun onSuccess(response: ListRes<Profile>) {
                        mAdapter?.addAll(SelectHolder.transform(response.results))
                        srl.isEnableLoadmore = response.isNext
                    }

                    override fun onFailure(errMsg: String?, response: ListRes<Profile>?, code: Int) {
                        DialogUtil.showError(mContext, errMsg)
                    }

                    override fun onFinish() {
                        super.onFinish()
                        srl.finishLoadmore()
                    }
                })
    }

//    object Util {
//        @JvmStatic
//        fun getGaiId(item: Profile) : String {
//            return "概率论ID：${item.gaiid}"
//        }
//    }

}